﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using UFIDA.U8.BJSOFT.LF.MES.WEBAPI.DBHelp;
using UFIDA.U8.BJSOFT.LF.MES.WEBAPI.Models;

namespace UFIDA.U8.BJSOFT.LF.MES.WEBAPI.Method
{
    public class AddRD02
    {
		public static string Insert(string filename, string jsons)
		{
			//LogException.WriteiLog(filename, "接收到的json:" + jsons, LogException.ilog, false);
			Result mr = new Result();
			List<ItemsItemR> lim = new List<ItemsItemR>();
			int row = 0;
			string res = "";
			bool flag = !string.IsNullOrEmpty(jsons);
			if (flag)
			{
				try
				{
					List<string> list = new List<string>();
					RD10 rd = JsonConvert.DeserializeObject<RD10>(jsons);
					string cCode = rd.cCode;
					int cou = rd.Items.Count;
					string moid = ""; string cvencode = "";
					bool flag2 = string.IsNullOrEmpty(cCode);
					if (flag2)
					{
						row = 1;
						res += "U8工单号不允许为空!检查cCode字段";
					}
					else
					{
                        for (int k = 0; k < cou; k++)
                        {
							string Autoid = rd.Items[k].Autoid;
							DataTable dtm = SQLHelper.GetDataTable(string.Concat(new string[]
							{
								"select moid from ",
								AddRD10.DBname,
								"..OM_MODetails where modetailsID='",
								Autoid,
								"'"
							}));
							int ifex = Convert.ToInt32(dtm.Rows.Count);
							bool flag3 = ifex > 0;
							if (flag3)
							{
								moid = dtm.Rows[0]["moid"].ToString();
								cCode = SQLHelper.GetString("select cCode from " + DBname + "..om_momain where moid=" + moid + "");
								cvencode = SQLHelper.GetString("select cvencode from " + DBname + "..om_momain where moid=" + moid + "");
							}
							else
							{
								row = 1;
								res = res + "U8工单[" + Autoid + "]查不到委外订单!";
							}
						}
						
					}
					string dCode = rd.dCode;
					bool flag4 = string.IsNullOrEmpty(dCode);
					if (flag4)
					{
						row = 1;
						res += "外部系统单号不允许为空!检查dCode字段";
					}
					else
					{
						int ifex2 = Convert.ToInt32(SQLHelper.GetString(string.Concat(new string[]
						{
							"select COUNT(*) from ",
							AddRD01.DBname,
							"..rdrecord01 where cCode='",
							dCode,
							"'"
						})));
						bool flag5 = ifex2 > 0;
						if (flag5)
						{
							row = 1;
							res = string.Concat(new string[]
							{
								res,
								"外部系统单号[",
								dCode,
								"]在U8系统已存在",
								filename,
								"信息!"
							});
						}
					}
					string dDate = rd.dDate;
					bool flag6 = !string.IsNullOrEmpty(dDate);
					if (flag6)
					{
						bool flag7 = !PublicMet.IsDate(dDate);
						if (flag7)
						{
							row = 1;
							res += "日期格式不正确!例：[2024-11-12]";
						}
					}
					else
					{
						row = 1;
						res += "日期不允许为空！检查dDate字段";
					}
					string cRdCode = rd.cRdCode;
					bool flag9 = string.IsNullOrEmpty(cRdCode);
					if (flag9)
					{
						row = 1;
						res += "类型不允许为空!检查cRdCode字段";
					}
					else
					{
						int ifex3 = Convert.ToInt32(SQLHelper.GetString(string.Concat(new string[]
						{
							"select COUNT(*) from ",
							AddRD01.DBname,
							"..Rd_Style where cRdCode='",
							cRdCode,
							"'"
						})));
						bool flag10 = ifex3 == 0;
						if (flag10)
						{
							row = 1;
							res = res + "类型[" + cRdCode + "]在U8系统不存在!";
						}
					}
					string cWhCode = rd.cWhCode;
					bool flag11 = string.IsNullOrEmpty(cWhCode);
					if (flag11)
					{
						row = 1;
						res += "仓库编码不允许为空!检查cWhCode字段";
					}
					else
					{
						int ifex4 = Convert.ToInt32(SQLHelper.GetString(string.Concat(new string[]
						{
							"select COUNT(*) from ",
							AddRD01.DBname,
							"..Warehouse where cWhCode='",
							cWhCode,
							"'"
						})));
						if (ifex4==0)
						{
							row = 1;
							res = res + "仓库编码[" + cWhCode + "]在U8系统不存在!";
						}
					}
					string cMaker = rd.cMaker;
					bool flag12 = string.IsNullOrEmpty(cMaker);
					if (flag12)
					{
						row = 1;
						res += "制单人不允许为空!检查cMaker字段";
					}
					else
					{
						string cMakers = PublicMet.CUSERNAME(cMaker);
						if (string.IsNullOrEmpty(cMakers))
						{
							row = 1;
							res += "未找到编码为[" + cMaker + "]的制单人员!";
						}
						else
						{
							cMaker = cMakers;
						}
					}
					string cHandler = rd.cHandler;
					bool flag13 = string.IsNullOrEmpty(cHandler);
					if (flag13)
					{
						row = 1;
						res += "审核人不允许为空!检查cHandler字段";
					}
					else
					{
						string cHandlers = PublicMet.CUSERNAME(cHandler);
						if (string.IsNullOrEmpty(cHandlers))
						{
							row = 1;
							res += "未找到编码为[" + cHandler + "]的审核人员!";
						}
						else
						{
							cHandler = cHandlers;
						}
					}
					string cDepCode = rd.cDepCode;
					bool flag15 = !string.IsNullOrEmpty(cDepCode);
					if (flag15)
					{
						int ifex5 = Convert.ToInt32(SQLHelper.GetString(string.Concat(new string[]
						{
							"select COUNT(*) from ",
							AddRD01.DBname,
							"..Department where cDepCode='",
							cDepCode,
							"'"
						})));
						bool flag16 = ifex5 == 0;
						if (flag16)
						{
							row = 1;
							res = res + "部门编码[" + cDepCode + "]在U8系统不存在!";
						}
					}
					else
					{
						row = 1;
						res = res + "部门编码不允许为空，检查cDepCode字段!";
					}
					
                    
					string cMemo = rd.cMemo;
					string cAcc_Id = AddRD01.DBname.Substring(7, 3);
					int fidrd = 0;
					int cidrd = 0;
					string sql = " select iFatherId,iChildId from UFSystem..UA_Identity where cAcc_Id='" + cAcc_Id + "' and cVouchType='rd' ";
					DataTable dtidrd = SQLHelper.GetDataTable(sql);
					bool flag17 = dtidrd.Rows.Count > 0;
					if (flag17)
					{
						fidrd = Convert.ToInt32(dtidrd.Rows[0]["iFatherId"].ToString());
						cidrd = Convert.ToInt32(dtidrd.Rows[0]["iChildId"].ToString());
					}
					else
					{
						sql = " insert into UFSystem..UA_Identity (cAcc_Id,cVouchType,iFatherId,iChildId)  values('" + cAcc_Id + "','rd',0,0) ";
						SQLHelper.ExecuteSql(sql);
					}
					fidrd++;
					SQLHelper.ExecuteSql("update UFSystem..UA_Identity set iFatherId=iFatherId+1 where cAcc_Id='" + cAcc_Id + "' and cVouchType='rd' ");
					string ID = "1" + string.Format("{0:D9}", fidrd);
					string Code = dCode;
					string csysbarcode = "||st01|" + Code;
					sql = string.Concat(new string[]
					{
						"insert into ",
						AddRD01.DBname,
						"..RdRecord01 (id,brdflag,cvouchtype,cbustype,csource,cwhcode,ddate,ccode,crdcode,cdepcode," +
						"cptcode,cvencode,cPersonCode ,cordercode,cmaker,bpufirst,vt_id,bisstqc,itaxrate,iexchrate," +
						"cexch_name,bomfirst,idiscounttaxtype,iswfcontrolled,dnmaketime,bredvouch,bcredit,iprintcount,cvenpuomprotocol,cHandler ," +
						" dVeriDate ,dnverifytime,ipurorderid,ipurarriveid,cARVCode,cMemo,cDefine10,csysbarcode)" +
						"values(",ID,",'1','01','委外加工', '委外订单','",cWhCode,"','",dDate,"','",Code,"','",cRdCode,"','",cDepCode,"', " +
						" '04',"+PublicMet.setvalue(2,cvencode)+",NULL, '",cCode,"','",cMaker,"','0','27','0','0','1', " +
						" '人民币','0','0','0',getdate(),'0','0','0',NULL,'",cHandler,"', " +
						" '",dDate,"',getdate(),'",moid,"',null,null,'",cMemo,"', NULL,'"+csysbarcode+"') "
					});
					LogException.WriteiLog(filename, "RD01主表新增语句:" + sql, LogException.ilog, false);
					list.Add(sql);
					//材料出库单
					fidrd++;
					list.Add("update UFSystem..UA_Identity set iFatherId=iFatherId+1 where cAcc_Id='" + cAcc_Id + "' and cVouchType='rd' ");
					string ID11 = "1" + string.Format("{0:D9}", fidrd);
					string Code11 = dCode;
					string csysbarcode2 = "||st11|" + Code11;
					string VT_ID2 = "65";
					sql = string.Concat(new string[]
					{
						//默认222委外发料
						"insert into ",
						 AddRD11.DBname,
						" ..rdrecord11(ID,bRdFlag,cVouchType,cBusType,cSource,cWhCode,dDate,cCode,cRdCode,cDepCode, " +
						" cHandler,bTransFlag,cMaker,dVeriDate,bpufirst,biafirst,iMQuantity,VT_ID,bIsSTQc,cPsPcode, " +
						" cMPoCode,iproorderid,bOMFirst,bFromPreYear,bIsComplement,iDiscountTaxType,ireturncount,iverifystate,iswfcontrolled,dnmaketime, " +
						" dnverifytime,bredvouch,bmotran,bHYVouch,iPrintCount,csysbarcode,cdefine10,cmemo,cvencode) " +
						" values('",ID11,"','0','11','领料','库存','",cWhCode,"','",dDate,"','",Code11,"','222','",cDepCode,"','",
						  cHandler,"',0,'",cMaker,"',convert(varchar(10),getdate(),23),0,0,'",0.ToString(),"','",VT_ID2,"',0,NULL," +
						" NULL,NULL,0,0,0,0,0,0,0,getdate(),getdate(),0,0,0,0,'",csysbarcode2,"',NULL,'",cMemo,"',NULL)"
					});
					list.Add(sql);

					for (int i = 0; i < cou; i++)
					{
						ItemsItemR mir = new ItemsItemR();
						string Autoid = rd.Items[i].Autoid;
						bool flag18 = string.IsNullOrEmpty(Autoid);
						if (flag18)
						{
							row = 1;
							res = res + "第[" + (i + 1).ToString() + "]行U8工单明细唯一标识ID不允许为空!检查Autoid字段";
						}
						else
						{
							int ifex6 = Convert.ToInt32(SQLHelper.GetString(string.Concat(new string[]
							{
								"select COUNT(*) from ",
								AddRD01.DBname,
								"..OM_MODetails where modetailsID='",
								Autoid,
								"'"
							})));
							bool flag19 = ifex6 == 0;
							if (flag19)
							{
								row = 1;
								res = string.Concat(new string[]
								{
									res,
									"第[",
									(i + 1).ToString(),
									"]行U8工单明细唯一ID[",
									Autoid,
									"]在U8系统不存在!"
								});
							}
						}
						string RowNo = rd.Items[i].RowNo;
						bool flag20 = string.IsNullOrEmpty(RowNo);
						if (flag20)
						{
							row = 1;
							res = res + "第[" + (i + 1).ToString() + "]行行号不允许为空!检查RowNo字段";
						}
						string cInvCode = rd.Items[i].cInvCode;
						bool flag21 = string.IsNullOrEmpty(cInvCode);
						if (flag21)
						{
							row = 1;
							res = res + "第[" + (i + 1).ToString() + "]行存货编码不允许为空!检查cInvCode字段";
						}
						else
						{
							int ifex7 = Convert.ToInt32(SQLHelper.GetString(string.Concat(new string[]
							{
								"select COUNT(*) from ",
								AddRD01.DBname,
								"..Inventory where cinvcode='",
								cInvCode,
								"'"
							})));
							bool flag22 = ifex7 == 0;
							if (flag22)
							{
								row = 1;
								res = string.Concat(new string[]
								{
									res,
									"第[",
									(i + 1).ToString(),
									"]行存货编码[",
									cInvCode,
									"]在U8系统不存在!"
								});
							}
						}
						string iQuantity = rd.Items[i].iQuantity;
						bool flag23 = string.IsNullOrEmpty(iQuantity);
						if (flag23)
						{
							row = 1;
							res = res + "第[" + (i + 1).ToString() + "]行数量不允许为空!检查iQuantity字段!";
						}
						else
						{
							bool flag24 = !PublicMet.IsNumberic(iQuantity);
							if (flag24)
							{
								row = 1;
								res = string.Concat(new string[]
								{
									res,
									"第[",
									(i + 1).ToString(),
									"]行数量[",
									iQuantity,
									"]非数字类型!"
								});
							}
						}
						string cBatch = rd.Items[i].cBatch;
						bool cba = Convert.ToBoolean(SQLHelper.GetString(string.Concat(new string[]
						{
							"select isnull(bInvBatch,0) from ",
							AddRD01.DBname,
							"..Inventory where cinvcode='",
							cInvCode,
							"'"
						})));
						if (cba)
						{
							bool flag26 = string.IsNullOrEmpty(cBatch);
							if (flag26)
							{
								row = 1;
								res = string.Concat(new string[]
								{
									res,
									"第[",
									(i + 1).ToString(),
									"]行存货[",
									cInvCode,
									"]进行批次管理,批次不允许为空,检查cBatch字段!"
								});
							}
						}
						string dMadeDate = rd.Items[i].dMadeDate;
						string cPosCode = rd.Items[i].cPosCode;
						bool flag27 = row == 0;
						if (flag27)
						{
							cidrd++;
							SQLHelper.ExecuteSql("update UFSystem..UA_Identity set iChildId=iChildId+1 where cAcc_Id='" + cAcc_Id + "' and cVouchType='rd' ");
							string autoid = "1" + string.Format("{0:D9}", cidrd);
							string cbsysbarcode = "||st01|" + Code + "|" + (i + 1).ToString();
							string sqlunit = string.Concat(new string[]
							{
								"select  cSTComUnitCode,isnull(iChangRate,NULL) iChangRate   from ",
								AddRD01.DBname,
								"..inventory i  left join ",
								AddRD01.DBname,
								"..ComputationUnit c  on i.cSTComUnitCode=c.cComunitCode  where cinvcode='",
								cInvCode,
								"'"
							});
							LogException.WriteiLog(filename, "采购入库辅计量单位编码查询语句：" + sqlunit, LogException.ilog, false);
							DataTable dtiv = SQLHelper.GetDataTable(sqlunit);
							bool flag28 = dtiv.Rows.Count > 0;
							string cAssUnit;
							string iinvexchrate;
							if (flag28)
							{
								cAssUnit = "'" + dtiv.Rows[0]["cSTComUnitCode"].ToString() + "'";
								bool flag29 = !string.IsNullOrEmpty(dtiv.Rows[0]["iChangRate"].ToString());
								if (flag29)
								{
									iinvexchrate = (dtiv.Rows[0]["iChangRate"].ToString() ?? "");
								}
								else
								{
									iinvexchrate = "NULL";
								}
							}
							else
							{
								cAssUnit = "NULL";
								iinvexchrate = "NULL";
							}
							decimal iUnitPrice = 0;
							sql = "select isnull(iUnitPrice,0) iUnitPrice from OM_MODetails where modetailsID='" + Autoid+"' ";
							DataTable dt = DBHelp.SQLHelper.GetDataTable(sql);
                            if (dt.Rows.Count>0)
                            {
								iUnitPrice = Convert.ToDecimal(dt.Rows[0]["iUnitPrice"].ToString());
                            }
							sql = string.Concat(new string[]
							{
								" insert into ",
								AddRD01.DBname,
								"..rdrecords01(autoid,id,cinvcode,inum,iquantity,iunitcost,iprice,iaprice," +
								"isquantity , isnum, imoney, ifnum, ifquantity, iposid, facost, inquantity, innum, cassunit," +
								"ioritaxcost,ioricost,iorimoney,ioritaxprice,iorisum,itaxrate,itaxprice," +
								"isum,btaxcost,cpoid,bcosting,bvmiused,iinvexchrate,iexpiratdatecalcu,iordertype," +
								"isotype,irowno ,cBatch ,iArrsId ,cbarvcode,cPosition,cbMemo,iOMoDID,iProcessFee ,iProcessCost)" +
								"values( '",autoid,"','",ID,"','",cInvCode,"',null,'",iQuantity,"',NULL,NULL,NULL," +
								"0,0,0,null,null, null,NULL,'",iQuantity,"',NULL,",cAssUnit,
								",NULL,NULL,NULL,NULL,NULL,NULL, NULL," +
								" NULL,0,'",cCode,"',1,null,",iinvexchrate,",0,0," +
								"0,'",(i + 1).ToString(),"', '",cBatch,"', null,null,NULL,NULL,'",Autoid,"',NULL,NULL) "
							});
							list.Add(sql);
							decimal iProcessFee = Convert.ToDecimal(iQuantity) * iUnitPrice;
							sql = " UPDATE rdrecords01 SET itaxrate = 13, bTaxCost = 1, iProcessCost ="+iUnitPrice+", iProcessFee ="+ iProcessFee + ", bgift = NULL, iposflag = NULL, iProductType = 0, iinvexchrate = 0," +
								" iVMISettleNum = NULL, iVMISettleQuantity = NULL, iSumBillQuantity = NULL, cbaccounter = NULL, cAssUnit = NULL where AutoID = '"+autoid+"'";
							list.Add(sql);

							string autoid11 = "1" + string.Format("{0:D9}", cidrd);
							string cbsysbarcode2 = "||st11|" + Code11 + "|" + (i + 1).ToString();
							sql = string.Concat(new string[]
							{
								"insert into ",
								AddRD11.DBname,
								"..rdrecords11(AutoID,ID,cInvCode,iQuantity,cBatch,iFlag,dVDate,cPosition," +
								" iNQuantity,dMadeDate,iMassDate,iMPoIds,cMassUnit,cmworkcentercode,bLPUseFree," +
								"iOriTrackID,bCosting,bVMIUsed,cmocode,invcode," +
								"imoseq,iopseq,copdesc,iExpiratDateCalcu,iorderdid, " +
								"iordertype,isotype,ipesodid,ipesotype,cpesocode," +
								"ipesoseq,irowno,cbsysbarcode,bcanreplace,iposflag," +
								" cItemCode,cName,cItem_class,cItemCName,cbMemo, " +
								"iProcessFee,comcode,cAssUnit,iinvexchrate,iOMoDID,iOMoMID)" +
								"values('",autoid11,"','",ID11,"','",cInvCode,"','",iQuantity,"',",PublicMet.setvalue(2,cBatch),",0,null,NULL,'",
								iQuantity,"',null,NULL,NULL,NULL,null,0," +
								" 0,1,0,NULL,",PublicMet.setvalue(2,cInvCode),",NULL,null,null,0,NULL," +
								"0,0,NULL,NULL,NULL," +
								" null ,'",(i + 1).ToString(),"','",cbsysbarcode2,"',NULL,NULL," +
								" NULL,NULL,NULL,NULL,NULL,NULL,NULL," +
								" ",PublicMet.setvalue(2,cAssUnit),",",iinvexchrate,",'",moid,"',NULL)"
							});
							list.Add(sql);

							list.Add(string.Concat(new string[]
							{
								"update ",AddRD01.DBname,"..OM_MODetails set iReceivedQTY =isnull(iReceivedQTY,0)+",iQuantity,"  where MODetailsID='",Autoid,"'"
							}));
							list.Add(string.Concat(new string[]
							{
								"insert into ",AddRD01.DBname,"..IA_ST_UnAccountVouch01(IDUN,IDSUN,cVouTypeUN,cBustypeUN) values ('",ID,"','",autoid,"','01','普通采购')"
							}));
							mir.Autoid = Autoid;
							mir.U8RowNo = (i + 1).ToString();
							mir.U8ID = autoid;
							lim.Add(mir);
						}
					}
					sql = string.Concat(new string[]
					{
						"exec ",
						AddRD01.DBname,
						"..pro_uptcurrentStock '",
						AddRD01.DBname,
						"','01','",
						ID,
						"'"
					});
					list.Add(sql);
					bool flag30 = row == 0;
					if (flag30)
					{
						int count = SQLHelper.ExecuteSqlTran(list);
						bool flag31 = count > 0;
						if (flag31)
						{
							res += "入库成功";
							mr.U8Code = dCode;
							mr.Items = lim;
							LogException.WriteiLog(filename, "RD01入库成功[" + dCode + "]", LogException.ilog, false);
						}
						else
						{
							row = 1;
							res += "入库失败";
						}
					}
				}
				catch (Exception ex)
				{
					row = 1;
					LogException.WriteiLog(filename, "RD01异常:" + ex.Message, LogException.ilog, true);
					res = res + "失败:" + ex.Message;
				}
			}
			else
			{
				row = 1;
				res += "未传任何数据!";
			}
			bool flag32 = row == 1;
			if (flag32)
			{
				mr.Code = "500";
				mr.Msg = res;
			}
			else
			{
				mr.Code = "200";
				mr.Msg = res;
			}
			return JsonConvert.SerializeObject(mr);
		}
		public static string DBname = ConfigurationManager.AppSettings["U8DBNAME"].ToString();
	}
}